//
//  EmailPasswordViewController.m
//  bitcoin
//
//  Created by caiyajun on 2018/5/7.
//  Copyright © 2018年 比特币. All rights reserved.
//

#import "EmailPasswordViewController.h"
#import "LCGrayButton.h"
#import "LoginSafeTableViewController.h"
#define mAlphaNum @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_"
@interface EmailPasswordViewController ()
@property (weak, nonatomic) IBOutlet UIButton *sureButton;
@property (weak, nonatomic) IBOutlet UITextField *phoneTF;
@property (weak, nonatomic) IBOutlet UITextField *messageTF;
@property (weak, nonatomic) IBOutlet UITextField *otherPasswordTF;
@property (weak, nonatomic) IBOutlet UIButton *eyeBtn;
- (IBAction)changeEyeAction:(UIButton *)sender;
@property (weak, nonatomic) IBOutlet LCGrayButton *sendCodeBtn;

@property (nonatomic, copy) NSString *email;//邮箱验证 1表示启用验证 0表示禁用验证
@property (nonatomic, copy) NSString *u_email;//用户验证邮箱
@property (nonatomic, copy) NSString *isSame;//验证邮箱和登陆邮箱账号是否一致 1相同
@property (nonatomic, copy) NSString *google;//谷歌验证  1表示启用验证 0表示禁用验证
@end

@implementation EmailPasswordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIBarButtonItem *back = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"arrowleft-icon"] style:UIBarButtonItemStylePlain target:self action:@selector(backAction:)];
    self.navigationItem.leftBarButtonItem = back;
    
    [_phoneTF setValue:[UIColor colorWithHexString:@"#616372"] forKeyPath:@"_placeholderLabel.textColor"];
    [_messageTF setValue:[UIColor colorWithHexString:@"#616372"] forKeyPath:@"_placeholderLabel.textColor"];
    [_otherPasswordTF setValue:[UIColor colorWithHexString:@"#616372"] forKeyPath:@"_placeholderLabel.textColor"];
    [_eyeBtn setImage:[UIImage imageNamed:@"open-icon"] forState:UIControlStateNormal];
    [_eyeBtn setImage:[UIImage imageNamed:@"close-icon"] forState:UIControlStateSelected];
    _eyeBtn.selected=YES;
    self.otherPasswordTF.secureTextEntry=YES;
    [self.sendCodeBtn addTarget: self action:@selector(startTime) forControlEvents:UIControlEventTouchUpInside];
    
    [self.sureButton setBackgroundImage:[UIImage imageWithColor:RGBColor(86, 54, 157)] forState:(UIControlStateHighlighted)];
    // Do any additional setup after loading the view.
}
- (void)backAction:(UIBarButtonItem *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)changeEyeAction:(UIButton *)sender {
    self.otherPasswordTF.enabled = NO;
    self.otherPasswordTF.secureTextEntry = !sender.selected;
    sender.selected = !sender.selected;
    self.otherPasswordTF.enabled = YES;
}
-(void)startTime{
    [self.view endEditing:YES];
    if (self.phoneTF.text.length==0) {
        [MBProgressHUD showError:@"请输入帐号"];
        return;
    }
    if ( ![CheckUtil validateEmail:self.phoneTF.text]) {
        [MBProgressHUD showError:@"请输入有效的邮箱地址!"];
        return;
    }
    [self changeShow];
    DebugLog(@"我点击了.... ");
    NSDictionary *param = @{@"accept_device" : self.phoneTF.text,
                            @"site" : @"3"
                            };
    [LSRequestManager postRequestWithURL:HUOBI(@"api/auth/sendYzm")
                                  params:param
                                 success:^(NSDictionary *responseData) {
                                     if ([responseData[@"ret"] integerValue ] == 0) {
                                         
                                     } else {
                                         [MBProgressHUD showError:responseData[@"msg"]];
                                     }
                                 }
                                 failure:^(NSError *error) {
                                     
                                 }
                                 showHUD:NO];
    
    
    
}
-(void)changeShow{
    __block int timeout = 59; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [self.sendCodeBtn setTitle:@"发送验证码" forState:UIControlStateNormal];
                self.sendCodeBtn.enabled = YES;
            });
        }else{
            //            int minutes = timeout / 60;
            int seconds = timeout % 60;
            NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [self.sendCodeBtn setTitle:[NSString stringWithFormat:@"重新获取%@秒",strTime] forState:UIControlStateNormal];
                self.sendCodeBtn.enabled = NO;
                
            });
            timeout--;
            
        }
    });
    dispatch_resume(_timer);
}









- (IBAction)changePasswordAction {
//    修改密码提交
    [self.view endEditing:YES];
    if (self.phoneTF.text.length==0) {
        [MBProgressHUD showError:@"请输入帐号"];
        return;
    }
    NSRange range = [self.phoneTF.text rangeOfString:@" "];
    if (range.location != NSNotFound) {
        [MBProgressHUD showError:@"请输入邮箱"];
        return;
    }
    
    
    if (self.messageTF.text.length==0) {
        [MBProgressHUD showError:@"请输入验证码"];
        return;
    }
    NSRange range1 = [self.messageTF.text rangeOfString:@" "];
    if (range1.location != NSNotFound) {
        [MBProgressHUD showError:@"请输入验证码"];
        return;
    }
    
    
    if (self.otherPasswordTF.text.length==0) {
        [MBProgressHUD showError:@"请输入密码"];
        return;
    }
    NSRange range2 = [self.otherPasswordTF.text rangeOfString:@" "];
    if (range2.location != NSNotFound) {
        [MBProgressHUD showError:@"请输入密码"];
        return;
    }
    NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:mAlphaNum] invertedSet];
    NSString *filtered = [[self.otherPasswordTF.text componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
    BOOL canChange = [self.otherPasswordTF.text isEqualToString:filtered];
    if (!canChange) {
        [MBProgressHUD showError:@"密码只能由大小写字母、数字及_符号组成"];
        return;
    }
    
    
    
    
    
    
    NSString * regex = @"(?![0-9A-Z]+$)(?![0-9a-z]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,12}$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    BOOL result = [pred evaluateWithObject:self.otherPasswordTF.text];
    if (!result){
        [MBProgressHUD showError:@"密码必须为8-12位，并最少包含大小写字母、数字"];
        return;
    }
//    判断是否需要进行谷歌验证
    NSDictionary *param = @{@"account" : self.phoneTF.text,};
    [LSRequestManager getRequestWithURL:HUOBI(@"api/user/securityByAccount")
                                 params:param
                                success:^(NSDictionary *responseData) {
                                    if ([responseData[@"ret"] integerValue ] == 0) {
                                        self.u_email=[NSString stringWithFormat:@"%@",responseData[@"data"][@"u_email"]];
                                        self.email=[NSString stringWithFormat:@"%@",responseData[@"data"][@"email"]];
                                        self.google=[NSString stringWithFormat:@"%@",responseData[@"data"][@"google"]];
                                        if ([self.u_email isEqualToString:self.phoneTF.text]) {
                                            self.isSame=@"1";
                                        }else{
                                            self.isSame=@"2";
                                        }
                                        if ([self.email isEqualToString:@"1"]||[self.google isEqualToString:@"1"]) {
                                            UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Login" bundle:nil];
                                            LoginSafeTableViewController *loginSafeCtrl = [sb instantiateViewControllerWithIdentifier:@"LoginSafeTableViewController"];
                                            loginSafeCtrl.pushType=@"forgetPassword";
                                            loginSafeCtrl.u_email=self.u_email;
                                            loginSafeCtrl.email=self.email;
                                            loginSafeCtrl.google=self.google;
                                            loginSafeCtrl.isSame=self.isSame;
                                            loginSafeCtrl.forgetEmail=self.phoneTF.text;
                                            loginSafeCtrl.forgetEmailSafe=self.messageTF.text;
                                            loginSafeCtrl.forgetNewPassword=self.otherPasswordTF.text;
                                            [self.navigationController pushViewController:loginSafeCtrl animated:YES];
                                        }else{
                                            [self submit];
                                        }
                                        
                                    } else {
                                        [MBProgressHUD showError:responseData[@"msg"]];
                                    }
                                }
                                failure:^(NSError *error) {
                                    
                                }
                                showHUD:NO];
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
}
-(void)submit{
    NSDictionary *param = @{@"login_val" : self.phoneTF.text,
                            @"reg_type" : @"2",
                            @"yzm" : self.messageTF.text,
                            @"new_login_pwd" : self.otherPasswordTF.text
                            };
    [LSRequestManager putRequestWithURL:HUOBI(@"api/auth/resetPwd")
                                  params:param
                                 success:^(NSDictionary *responseData) {
                                     if ([responseData[@"ret"] integerValue ] == 0) {
                                         
                                         [self.navigationController popViewControllerAnimated:YES];
                                         
                                         
                                         
                                     } else {
                                         [MBProgressHUD showError:responseData[@"msg"]];
                                     }
                                 }
                                 failure:^(NSError *error) {
                                     
                                 }
                                 showHUD:NO];
}
@end
